<!-- components/charts/LineChart.vue -->
<template>
  <BaseChart :options="chartOptions" :height="height" :show-empty="showEmpty" @chart-ready="onChartReady"
    @refresh="$emit('refresh')" />
</template>

<script setup>
import { computed } from 'vue'
import BaseChart from './BaseChart.vue'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  height: {
    type: String,
    default: '400px'
  },
  config: {
    type: Object,
    default: () => ({})
  },
  showEmpty: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['chartReady', 'refresh'])

// 获取折线图配置
const lineOption = computed(() => props.config.option || {})

// 获取所有数组类型的字段
const arrayFields = computed(() => {
  const data = props.data || {}
  return Object.keys(data).filter(key =>
    Array.isArray(data[key]) && data[key].length > 0
  )
})

// 获取所有数值数组字段
const numericArrayFields = computed(() => {
  const data = props.data || {}
  return arrayFields.value.filter(key => {
    const arr = data[key]
    return arr.every(item => typeof item === 'number')
  })
})

// 检查是否有有效数据
const hasValidData = computed(() => {
  const xAxisKey = lineOption.value.xAxis
  const yAxisKeys = lineOption.value.yAxis || []

  if (!xAxisKey || yAxisKeys.length === 0) {
    return false
  }

  const data = props.data || {}
  const xData = data[xAxisKey]
  const hasYData = yAxisKeys.some(key => {
    const yData = data[key]
    return yData && Array.isArray(yData) && yData.length > 0
  })

  return xData && Array.isArray(xData) && xData.length > 0 && hasYData
})

const chartOptions = computed(() => {
  const data = props.data || {}
  const xAxisKey = lineOption.value.xAxis
  const yAxisKeys = lineOption.value.yAxis || []

  if (!hasValidData.value) {
    return {
      title: {
        text: props.config.title || '折线图',
        left: 'center'
      },
      series: []
    }
  }

  const xData = data[xAxisKey] || []

  // 格式化数字
  const formatNumber = (value) => {
    if (lineOption.value.decimalPlaces > 0) {
      return value.toFixed(lineOption.value.decimalPlaces)
    }
    return value.toString()
  }

  return {
    title: {
      text: props.config.title || '折线图',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },

    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let result = `${params[0].axisValue}<br/>`
        params.forEach(param => {
          const value = formatNumber(param.value)
          result += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color}"></span>`
          result += `${param.seriesName}: ${value}<br/>`
        })
        return result
      }
    },

    legend: {
      data: yAxisKeys,
      bottom: 0
    },

    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },

    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        fontSize: lineOption.value.fontSize
      }
    },

    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: lineOption.value.fontSize
      }
    },

    series: yAxisKeys.map((key, index) => {
      const seriesData = data[key] || []
      const color = lineOption.value.colors?.[index % lineOption.value.colors.length] || '#5470c6'

      return {
        name: key,
        type: 'line',
        data: seriesData,
        smooth: lineOption.value.smooth,
        symbol: lineOption.value.showSymbol ? 'circle' : 'none',
        symbolSize: 6,
        itemStyle: {
          color: color
        },
        label: {
          show: lineOption.value.showLabel,
          fontSize: lineOption.value.fontSize,
          formatter: (params) => formatNumber(params.value)
        },
        lineStyle: {
          color: color
        }
      }
    })
  }
})

const onChartReady = (chart) => {
  emit('chartReady', chart)
}

defineExpose({
  arrayFields,
  numericArrayFields
})
</script>